<template>
  <div class="archive-appraisal-destruction-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>档案鉴定与销毁</span>
      </div>
      <div class="search-bar">
        <el-input placeholder="搜索销毁原因或备注" v-model="searchQuery" class="input-with-select" @keyup.enter.native="fetchDestructionRequests">
          <el-button slot="append" icon="el-icon-search" @click="fetchDestructionRequests"></el-button>
        </el-input>
        <el-select v-model="searchStatus" placeholder="按状态筛选" clearable @change="fetchDestructionRequests" style="margin-left: 10px;">
          <el-option label="待处理" value="pending"></el-option>
          <el-option label="已批准" value="approved"></el-option>
          <el-option label="已拒绝" value="rejected"></el-option>
          <el-option label="已完成" value="completed"></el-option>
        </el-select>
        <el-button type="primary" @click="openSubmitRequestDialog" v-if="hasPermission('档案管理员')" style="margin-left: 10px;">申请销毁</el-button>
      </div>
      <el-table :data="destructionRequests" style="width: 100%">
        <el-table-column prop="destructionId" label="销毁ID" width="80"></el-table-column>
        <el-table-column prop="archiveTitle" label="档案标题" width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="requesterName" label="申请人" width="120"></el-table-column>
        <el-table-column prop="reason" label="销毁原因" width="150" show-overflow-tooltip></el-table-column>
        <el-table-column prop="requestTime" label="申请时间" width="180"></el-table-column>
        <el-table-column prop="approvalStatus" label="审批状态" width="100" :formatter="statusFormatter"></el-table-column>
        <el-table-column prop="approverName" label="审批人" width="120"></el-table-column>
        <el-table-column prop="approvalTime" label="审批时间" width="180"></el-table-column>
        <el-table-column prop="destructionDate" label="销毁日期" width="180"></el-table-column>
        <el-table-column prop="notes" label="备注" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="success"
              @click="handleApprove(scope.row)"
              v-if="scope.row.approvalStatus === 'pending' && hasPermission('企业领导')">批准</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleReject(scope.row)"
              v-if="scope.row.approvalStatus === 'pending' && hasPermission('企业领导')">拒绝</el-button>
            <el-button
              size="mini"
              type="primary"
              @click="handleExecute(scope.row)"
              v-if="scope.row.approvalStatus === 'approved' && hasPermission('档案管理员')">执行销毁</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalRequests">
      </el-pagination>
    </el-card>

    <!-- 提交销毁申请对话框 -->
    <el-dialog
      title="提交销毁申请"
      :visible.sync="submitRequestDialogVisible"
      width="60%"
      :before-close="closeSubmitRequestDialog">
      <el-form :model="submitRequestForm" ref="submitRequestForm" label-width="100px" :rules="submitRequestRules">
        <el-form-item label="选择档案" prop="archiveId">
          <el-select v-model="submitRequestForm.archiveId" placeholder="请选择要销毁的档案" filterable @change="handleArchiveSelectionChange">
            <el-option
              v-for="item in archivesForSelection"
              :key="item.archiveId"
              :label="item.title + ' (ID: ' + item.archiveId + ')'"
              :value="item.archiveId">
            </el-option>
          </el-select>
        </el-form-item>
        
        <!-- 显示选中档案的详细信息 -->
        <div v-if="selectedArchive" class="selected-archive-info">
          <h4>档案详情</h4>
          <el-descriptions :column="2" border size="small">
            <el-descriptions-item label="档案标题">{{ selectedArchive.title }}</el-descriptions-item>
            <el-descriptions-item label="档案类型">{{ selectedArchive.archiveType }}</el-descriptions-item>
            <el-descriptions-item label="保密等级">{{ selectedArchive.securityLevel }}</el-descriptions-item>
            <el-descriptions-item label="物理位置">{{ selectedArchive.physicalLocation }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ selectedArchive.createdAt }}</el-descriptions-item>
            <el-descriptions-item label="状态">{{ selectedArchive.status }}</el-descriptions-item>
          </el-descriptions>
          
          <!-- 文档内容展示 -->
          <div class="ocr-content-section" v-if="selectedArchive.ocrContent">
            <h5>文档内容</h5>
            <el-input
              type="textarea"
              :rows="4"
              v-model="selectedArchive.ocrContent"
              :readonly="true"
              placeholder="无文档内容">
            </el-input>
          </div>
          <div class="ocr-content-section" v-else>
            <h5>文档内容</h5>
            <el-alert
              title="该档案没有文档内容"
              type="info"
              :closable="false"
              show-icon>
            </el-alert>
          </div>
        </div>
        
        <el-form-item label="销毁原因" prop="reason">
          <el-input type="textarea" v-model="submitRequestForm.reason" placeholder="请输入销毁原因"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeSubmitRequestDialog">取 消</el-button>
        <el-button type="primary" @click="submitDestructionRequest('submitRequestForm')">提 交</el-button>
      </span>
    </el-dialog>

    <!-- 审批/拒绝对话框 -->
    <el-dialog
      :title="approveRejectDialogTitle"
      :visible.sync="approveRejectDialogVisible"
      width="30%"
      :before-close="closeApproveRejectDialog">
      <el-input
        type="textarea"
        :rows="4"
        placeholder="请输入备注"
        v-model="approveRejectNotes">
      </el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeApproveRejectDialog">取 消</el-button>
        <el-button type="primary" @click="confirmApproveRejectAction">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 执行销毁对话框 -->
    <el-dialog
      title="执行销毁"
      :visible.sync="executeDestructionDialogVisible"
      width="30%"
      :before-close="closeExecuteDestructionDialog">
      <el-input
        type="textarea"
        :rows="4"
        placeholder="请输入销毁过程记录"
        v-model="destructionProcessRecord">
      </el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeExecuteDestructionDialog">取 消</el-button>
        <el-button type="primary" @click="confirmExecuteDestruction">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import service from '@/utils/request';

export default {
  name: 'ArchiveAppraisalDestruction',
  data() {
    return {
      destructionRequests: [],
      archivesForSelection: [], // For the submit request dropdown
      currentPage: 1,
      pageSize: 10,
      totalRequests: 0,
      searchQuery: '',
      searchStatus: '',
      userRole: '',

      submitRequestDialogVisible: false,
      submitRequestForm: {
        archiveId: null,
        reason: '',
      },
      submitRequestRules: {
        archiveId: [{ required: true, message: '请选择档案', trigger: 'change' }],
        reason: [{ required: true, message: '请输入销毁原因', trigger: 'blur' }],
      },

      approveRejectDialogVisible: false,
      approveRejectDialogTitle: '',
      approveRejectNotes: '',
      currentActionRequest: null, // Stores the request being acted upon (approve/reject)
      actionType: '', // 'approve' or 'reject'

      executeDestructionDialogVisible: false,
      destructionProcessRecord: '',
      currentExecuteRequest: null, // Stores the request being executed
      selectedArchive: null,
    };
  },
  created() {
    const user = JSON.parse(localStorage.getItem('user'));
    if (user && user.role) {
      this.userRole = user.role;
    }
    this.fetchDestructionRequests();
    this.fetchArchivesForSelection();
  },
  methods: {
    hasPermission(...roles) {
      return roles.includes(this.userRole);
    },
    statusFormatter(row, column, cellValue) {
      const statusMap = {
        'pending': '待处理',
        'approved': '已批准',
        'rejected': '已拒绝',
        'completed': '已完成',
      };
      return statusMap[cellValue] || cellValue;
    },
    fetchDestructionRequests() {
      service.get('/archive-destruction/list', {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          status: this.searchStatus,
          search: this.searchQuery
        }
      })
      .then(res => {
        if (res.data.code === 200) {
          this.destructionRequests = res.data.data.records;
          this.totalRequests = res.data.data.total;
        } else {
          this.$message.error(res.data.message || '获取销毁请求列表失败');
        }
      })
      .catch(error => {
        console.error("Error fetching destruction requests:", error);
        this.$message.error('获取销毁请求列表失败');
      });
    },
    fetchArchivesForSelection() {
      service.get('/archive/list', {
        params: {
          pageNum: 1,
          pageSize: 9999 // Fetch a large number to ensure all are available for selection
        }
      })
      .then(res => {
        if (res.data.code === 200) {
          // Only show archives that are 'active' and not already 'destroyed'
          this.archivesForSelection = res.data.data.records.filter(archive => archive.status === 'active');
        } else {
          this.$message.error(res.data.message || '获取档案列表失败');
        }
      })
      .catch(error => {
        console.error("Error fetching archives for selection:", error);
        this.$message.error('获取档案列表失败');
      });
    },
    openSubmitRequestDialog() {
      this.submitRequestDialogVisible = true;
      if (this.$refs.submitRequestForm) {
        this.$refs.submitRequestForm.resetFields();
      }
      this.submitRequestForm = { archiveId: null, reason: '' };
      this.fetchArchivesForSelection(); // Ensure the latest archives are fetched
    },
    closeSubmitRequestDialog() {
      this.submitRequestDialogVisible = false;
      if (this.$refs.submitRequestForm) {
        this.$refs.submitRequestForm.resetFields();
      }
    },
    submitDestructionRequest(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          service.post('/archive-destruction/submit', this.submitRequestForm)
            .then(res => {
              if (res.data.code === 200) {
                this.$message.success(res.data.message || '销毁申请提交成功');
                this.closeSubmitRequestDialog();
                this.fetchDestructionRequests(); // Refresh the list
              } else {
                this.$message.error(res.data.message || '销毁申请提交失败');
              }
            })
            .catch(error => {
              console.error("Error submitting destruction request:", error);
              this.$message.error('销毁申请提交失败');
            });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    handleApprove(row) {
      this.currentActionRequest = row;
      this.actionType = 'approve';
      this.approveRejectDialogTitle = '批准销毁请求';
      this.approveRejectDialogVisible = true;
    },
    handleReject(row) {
      this.currentActionRequest = row;
      this.actionType = 'reject';
      this.approveRejectDialogTitle = '拒绝销毁请求';
      this.approveRejectDialogVisible = true;
    },
    confirmApproveRejectAction() {
      if (!this.currentActionRequest) return;

      const url = this.actionType === 'approve' ? `/archive-destruction/approve/${this.currentActionRequest.destructionId}` : `/archive-destruction/reject/${this.currentActionRequest.destructionId}`;
      const payload = this.approveRejectNotes; // Send notes directly as request body for POST

      service.post(url, payload, {
        headers: {
          'Content-Type': 'text/plain'
        }
      })
      .then(res => {
        if (res.data.code === 200) {
          this.$message.success(res.data.message || `${this.approveRejectDialogTitle}成功`);
          this.fetchDestructionRequests(); // Refresh the list
          this.closeApproveRejectDialog();
        } else {
          this.$message.error(res.data.message || `${this.approveRejectDialogTitle}失败`);
        }
      })
      .catch(error => {
        console.error(`${this.approveRejectDialogTitle} failed:`, error);
        this.$message.error(`${this.approveRejectDialogTitle}失败`);
      });
    },
    closeApproveRejectDialog() {
      this.approveRejectDialogVisible = false;
      this.approveRejectDialogTitle = '';
      this.approveRejectNotes = '';
      this.currentActionRequest = null;
      this.actionType = '';
    },
    handleExecute(row) {
      this.currentExecuteRequest = row;
      this.executeDestructionDialogVisible = true;
    },
    confirmExecuteDestruction() {
      if (!this.currentExecuteRequest) return;

      const url = `/archive-destruction/execute/${this.currentExecuteRequest.destructionId}`;
      const payload = this.destructionProcessRecord;

      service.post(url, payload, {
        headers: {
          'Content-Type': 'text/plain'
        }
      })
      .then(res => {
        if (res.data.code === 200) {
          this.$message.success(res.data.message || '执行销毁成功');
          this.fetchDestructionRequests(); // Refresh the list
          this.closeExecuteDestructionDialog();
        } else {
          this.$message.error(res.data.message || '执行销毁失败');
        }
      })
      .catch(error => {
        console.error("Execute destruction failed:", error);
        this.$message.error('执行销毁失败');
      });
    },
    closeExecuteDestructionDialog() {
      this.executeDestructionDialogVisible = false;
      this.destructionProcessRecord = '';
      this.currentExecuteRequest = null;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchDestructionRequests();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchDestructionRequests();
    },
    handleArchiveSelectionChange(value) {
      this.selectedArchive = this.archivesForSelection.find(archive => archive.archiveId === value) || null;
    },
  }
}
</script>

<style scoped>
.archive-appraisal-destruction-container {
  padding: 20px;
}
.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}
.input-with-select {
  width: 300px;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}
.box-card {
  width: 100%;
}
.selected-archive-info {
  margin-bottom: 20px;
}
.ocr-content-section {
  margin-bottom: 20px;
}
</style> 